package com.zsj.Tree;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @Author zsj
 * @Version 1.0
 * @Date 2024/4/14 9:23
 * @Description 翻转二叉树
 */
public class TreeFlip {
    public static void main(String[] args) {
        TreeNode treeNode = new TreeNode(1
                , new TreeNode(2, new TreeNode(4), null),
                new TreeNode(3, new TreeNode(5, new TreeNode(7), null), new TreeNode(6)));
        new TreeFlip().treeFlip(treeNode);

        //层序遍历一下看看
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(treeNode);
        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode poll = queue.poll();
                System.out.println(poll.val);
                if (poll.left != null) queue.offer(poll.left);
                if (poll.right != null) queue.offer(poll.right);
            }
        }
    }

    public TreeNode treeFlip(TreeNode node) {
        flip(node);
        return node;
    }


    public void flip(TreeNode node) {
        if (node == null) return;
        TreeNode left = node.left;
        node.left = node.right;
        node.right = left;
        flip(node.left);
        flip(node.right);
    }
}
